
#%%合并pdf，剔除首页

"""
合并pdf，剔除首页
"""
import PyPDF2 as pp
import os
_a_files = []
for _f in os.listdir('.'):
    if _f.endswith('.pdf'):
        _a_files.append(_f)
_a_files.sort(key=str.lower)
print(_a_files)
_pdf_wr = pp.PdfWriter()
for _f2 in _a_files:
    _pdf_obj = open(_f2, 'rb')
    _pdf_r = pp.PdfReader(_pdf_obj)
    for _page_num in range(1, len(_pdf_r.pages)):
        _page_obj = _pdf_r.pages[_page_num]
        _pdf_wr.add_page(_page_obj)
_pdf_out = open('combined.pdf', 'wb')
_pdf_wr.write(_pdf_out)
_pdf_out.close()


#%%合并pdf，不剔除首页

"""
合并pdf，不剔除首页
"""
import PyPDF2 as pp
import os
_a_files = []
for _f in os.listdir('.'):
    if _f.endswith('.pdf'):
        _a_files.append(_f)
_a_files.sort(key=str.lower)
print(_a_files)
_pdf_wr = pp.PdfWriter()
for _f2 in _a_files:
    _pdf_obj = open(_f2, 'rb')
    _pdf_r = pp.PdfReader(_pdf_obj)
    for _page_num in range(len(_pdf_r.pages)):
        _page_obj = _pdf_r.pages[_page_num]
        _pdf_wr.add_page(_page_obj)
_pdf_out = open('combined.pdf', 'wb')
_pdf_wr.write(_pdf_out)
_pdf_out.close()



#%%合并pro开头的pdf

"""
合并pro开头的pdf
可以考虑使用_分割文件名，然后将第一部分相同的文件合并，更具备一般性

"""
import PyPDF2 as pp
import os, re
_a_files = []
for _f in os.listdir('.'):
    if re.match('pro.*?.pdf', _f):
        _a_files.append(_f)
_a_files.sort(key=str.lower)
print(_a_files)
_pdf_wr = pp.PdfWriter()
for _f2 in _a_files:
    _pdf_obj = open(_f2, 'rb')
    _pdf_r = pp.PdfReader(_pdf_obj)
    for _page_num in range(len(_pdf_r.pages)):
        _page_obj = _pdf_r.pages[_page_num]
        _pdf_wr.add_page(_page_obj)
_pdf_out = open('pro.pdf', 'wb')
_pdf_wr.write(_pdf_out)
_pdf_out.close()



#%%合并文件名结尾带_1, _2的pdf

"""
合并文件名结尾带_1, _2的pdf
"""
import PyPDF2 as pp
import os, re
_path = 'Z:/virtual_share/合并pdf'
os.chdir(_path)
_a_files = []
for _f in os.listdir('.'):
    if re.match('.*?_\\d.pdf', _f):
        _a_files.append(_f)
_a_files.sort(key=str.lower)
print(_a_files)
_pdf_wr = pp.PdfWriter()
for _f2 in _a_files:
    _pdf_obj = open(_f2, 'rb')
    _pdf_r = pp.PdfReader(_pdf_obj)
    for _page_num in range(len(_pdf_r.pages)):
        _page_obj = _pdf_r.pages[_page_num]
        _pdf_wr.add_page(_page_obj)
    _pdf_obj.close()
_pdf_out = open('pro.pdf', 'wb')
_pdf_wr.write(_pdf_out)
_pdf_out.close()



#%%练习代码

import PyPDF2 as pp
import os, re
_path = 'D:/主被动归档/test_for_code'
os.chdir(_path)
_a_files = []
for _f in os.listdir('.'):
    if re.match('.*pdf', _f):
        _a_files.append(_f)
_a_files.sort(key=str.lower)
_pdf_wr = pp.PdfWriter()
for _f2 in _a_files:
    _pdf_obj = open(_f2, 'rb')
    _pdf_r = pp.PdfReader(_pdf_obj)
    for _page_num in range(len(_pdf_r.pages)):
        _page_obj = _pdf_r.pages[_page_num]
        _pdf_wr.add_page(_page_obj)
_pdf_out = open('pro.pdf', 'wb')
_pdf_wr.write(_pdf_out)
_pdf_out.close()


